package com.huiyuanai.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.huiyuanai.dao.Role;
import com.huiyuanai.dao.User;
import com.huiyuanai.service.role.RoleService;
import com.huiyuanai.service.role.RoleServiceImpl;
import com.huiyuanai.service.user.UserService;
import com.huiyuanai.service.user.UserServiceImpl;
import com.huiyuanai.util.Constans;
import com.huiyuanai.util.PageSupport;
import com.mysql.cj.util.StringUtils;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: liwan
 * @Description:
 * @Date: create in 2021/10/5
 */
public class UserServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method != null && "savepwd".equals(method)) {
            savePwd(req, resp);
        } else if (method != null && "pwdmodify".equals(method)) {
            pwdModify(req, resp);
        } else if (method != null && "query".equals(method)) {
            query(req, resp);
        } else if (method != null && "add".equals(method)) {
            add(req, resp);
        } else if (method != null && "getrolelist".equals(method)) {
            getRoleList(req, resp);
        } else if (method != null && "ucexist".equals(method)) {
            ucexist(req, resp);
        } else if ((method != null) && "deluser".equals(method)) {
            delUser(req, resp);
        } else if ((method != null) && "view".equals(method)) {
            viewUser(req, resp);
        } else if ((method != null) && "modify".equals(method)) {
            modify(req, resp);
        } else if ((method != null) && "modifyexe".equals(method)) {
            modifyExe(req, resp);
        }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    //修改密码
    public void savePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Object attribute = session.getAttribute(Constans.USER_SESSION);
        int flag = 0;
        //获取输入的密码
        String newpassword = req.getParameter("newpassword");
        //判断一下是否存在
        if (!StringUtils.isNullOrEmpty(newpassword)) {
            //调用service层
            UserService service = new UserServiceImpl();
            try {
                flag = service.updataPWD(newpassword, ((User) attribute).getId());
                if (flag > 0) {
                    req.setAttribute("message", "修改密码成功,请退出重新登录");
                    //修改成功移除session
                    session.removeAttribute(Constans.USER_SESSION);
                    //跳转页面
                } else {
                    req.setAttribute("message", "修改密码失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            req.setAttribute("message", "新密码有误");
        }
        req.getRequestDispatcher("/jsp/user/pwdmodify.jsp").forward(req, resp);
    }

    //验证密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp) {

        Object user = req.getSession().getAttribute(Constans.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        HashMap<String, String> resultMap = new HashMap<String, String>();

        if (user == null) {
            //Session失效了
            resultMap.put("result", "sessionerror");
        } else if (StringUtils.isNullOrEmpty(oldpassword)) {
            resultMap.put("result", "error");
        } else {
            if (((User) user).getUserPassword().equals(oldpassword)) {
                resultMap.put("result", "true");
            } else {
                resultMap.put("result", "false");
            }
        }
        //设置编码
        resp.setContentType("application/json");
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //转换成json
        writer.write(JSONArray.toJSONString(resultMap));
        //清理缓存
        writer.flush();
        //关闭流
        writer.close();
    }

    //分页查询
    public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //页码工具类
        PageSupport pageSupport = new PageSupport();
        //获得总共的页数 需要拿到限定条件
        UserService userService = new UserServiceImpl();
        //从前端获取数据
        String userName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int userRole = 0;
        if (temp != null && !"".equals(temp)) {
            userRole = Integer.parseInt(temp);
        }
        int count = 0;
        try {
            count = userService.userCount(userName, userRole);
            //设置页面容量
            pageSupport.setPageSize(Constans.PAGE);
            //设置总数量
            pageSupport.setTotalCount(count);
            //设置当前页码
            pageSupport.setCurrentPageNo(Integer.parseInt((pageIndex == null) ? "1" : pageIndex));
            //展示数据  查询user
            List<User> userList = userService.getUserList(userName, userRole, pageSupport.getCurrentPageNo(), pageSupport.getPageSize(), null);
            req.setAttribute("userList", userList);

            //查询职务
            RoleService roleService = new RoleServiceImpl();
            List<Role> roleList = roleService.getRoleList();
            req.setAttribute("roleList", roleList);

            //传递页码相关的参数
            req.setAttribute("totalCount", pageSupport.getTotalCount());
            req.setAttribute("currentPageNo", pageSupport.getCurrentPageNo());
            req.setAttribute("totalPageCount", pageSupport.getTotalPageCount());
            req.setAttribute("queryUserName", userName);
            req.setAttribute("queryUserRole", userRole);
        } catch (Exception e) {
            e.printStackTrace();
        }
        req.getRequestDispatcher("/jsp/user/userlist.jsp").forward(req, resp);
    }

    //新增用户
    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        UserService userService = new UserServiceImpl();
        int result = 0;
        //拿到前端的数据
        User user = new User();
        user.setUserCode(req.getParameter("userCode"));
        user.setUserName(req.getParameter("userName"));
        user.setUserPassword(req.getParameter("userPassword"));
        user.setGender(Integer.parseInt(req.getParameter("gender")));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-mm-dd").parse(req.getParameter("birthday")));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(req.getParameter("phone"));
        user.setAddress(req.getParameter("address"));
        user.setUserRole(Integer.parseInt(req.getParameter("userRole")));
        user.setCreatedBy(((User) req.getSession().getAttribute(Constans.USER_SESSION)).getId());
        user.setCreationDate(new Date());
        try {
            result = userService.addUser(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //判断一下是否成功
        if (result > 0) {
            resp.sendRedirect(req. getContextPath() + "/jsp/user.do?method=query");
        } else {
            req.getRequestDispatcher("/jsp/user/useradd.jsp").forward(req, resp);
        }
    }

    //新增用户role数据传递
    public void getRoleList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取role全部数据
        RoleService roleService = new RoleServiceImpl();
        List<Role> roleList = null;
        try {
            roleList = roleService.getRoleList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将map转换为json传到前端
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write(JSON.toJSONString(roleList));
        //释放资源
        writer.flush();
        writer.close();
    }

    //判断用户编码是否存在
    public void ucexist(HttpServletRequest req, HttpServletResponse resp) {
        UserService userService = new UserServiceImpl();
        String userCode = req.getParameter("userCode");
        Map<Object, Object> map = new HashMap<Object, Object>();
        int result = 0;
        try {
            result = userService.isUserCode(userCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //判断并设置返回值
        if (result > 0) {
            map.put("userCode", "exist");
        }
        PrintWriter writer = null;
        resp.setContentType("application/json; charset=utf-8");
        try {
            writer = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.write(JSON.toJSONString(map));
        writer.flush();
        writer.close();
    }

    //删除用户
    public void delUser(HttpServletRequest req, HttpServletResponse resp) {
        UserService userService = new UserServiceImpl();
        String uid = req.getParameter("uid");
        int delID = Integer.parseInt(uid);
        Map<Object, Object> map = new HashMap<Object, Object>();
        if (delID <= 0) {
            map.put("delResult", "notexist");
        } else {
            int result = 0;
            try {
                result = userService.userDel(uid);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (result > 0) {
                map.put("delResult", "true");
            } else {
                map.put("delResult", "false");
            }
        }
        resp.setContentType("application/json; charset=utf-8");
        try {
            PrintWriter writer = resp.getWriter();
            writer.write(JSON.toJSONString(map));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //详细信息
    public void viewUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String usercode = req.getParameter("uid");
        UserService userService = new UserServiceImpl();
        List<User> userList = null;
        try {
            userList = userService.getUserList(null, 0, 0, 0, usercode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        User user = userList.get(0);
        req.setAttribute("user", user);
        //跳转
        req.getRequestDispatcher("/jsp/user/userview.jsp").forward(req, resp);

    }

    //更新用户显示数据
    public void modify(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获得用户数据
        String uid = req.getParameter("uid");
        UserService userService = new UserServiceImpl();
        List<User> userList = null;
        User user = null;
        userList = userService.getUserList(null, 0, 0, 0, uid);
        user = userList.get(0);
        req.setAttribute("user", user);
        req.getRequestDispatcher("/jsp/user/usermodify.jsp").forward(req, resp);
    }

    //更新用户
    public void modifyExe(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //从前端获取数据
        String uid = req.getParameter("uid");
        UserService userService = new UserServiceImpl();
        User user = new User();
        user.setId(Integer.parseInt(uid));
        user.setUserName(req.getParameter("userName"));
        user.setGender(Integer.parseInt(req.getParameter("gender")));
        user.setBirthday(new SimpleDateFormat("yyyy-mm-dd").parse(req.getParameter("birthday")));
        user.setPhone(req.getParameter("phone"));
        user.setAddress(req.getParameter("address"));
        user.setUserRole(Integer.parseInt(req.getParameter("userRole")));
        int result = userService.updataUser(user);
        if (result > 0) {
            resp.sendRedirect("/jsp/user.do?method=query");
        }else {
            req.setAttribute("user", user);
            req.getRequestDispatcher("/jsp/user/usermodify.jsp").forward(req, resp);
        }
    }
}
